package example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class JwtPractice {

    public static void main(String[] args) {
        // 创建
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId("1001") /*登陆id*/
                .setSubject("小明") /*登陆名称*/
                .setIssuedAt(new Date()) /*登陆事件*/
                .signWith(SignatureAlgorithm.HS256, "practice") /*SignatureAlgorithm.HS256:编码； 盐：practice*/
                .setExpiration(new Date(System.currentTimeMillis() + 60000))/* 过期时间 1分钟 */
//                .setClaims(new HashMap<>())
                .addClaims(new HashMap<>());
//                .claim("role", "admin");

        System.out.println(jwtBuilder.compact());

        // 解析
        Claims practice = Jwts.parser()
                .setSigningKey("practice")
                .parseClaimsJws(jwtBuilder.compact())
//                .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMDAxIiwic3ViIjoi5bCP5piOIiwiaWF0IjoxNTg3Njk5MTY0LCJleHAiOjE1ODc2OTkyMDB9.RgVXn-2BGIvQVfksQGSk-lXe9SbpP_zetLR-Lm7DazI")
                .getBody();
        System.out.println("id:" + practice.getId());
        System.out.println("name:" + practice.getSubject());
        System.out.println("sign in date:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(practice.getIssuedAt()));
        System.out.println("over date:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(practice.getExpiration()));
        System.out.println("role date:" + practice.get("role"));
    }
}
